# -*- coding: UTF-8 -*-
import os
import time
import cv2

from lj_tool import tool_id, tool_run


class LJStreamCv():
    def __init__(self, url) -> None:
        self.url = url
        self.is_stop = False

    def start(self):
        print(f"LJ - 开始执行视频流[{self.url}]转发...")
        # 打开视频流
        cap = cv2.VideoCapture(self.url)

        # 检查是否成功打开视频流
        if not cap.isOpened():
            print(f"无法打开视频流[{self.url}]")
            return

        while not tool_run.tool_run_g.get("is_golbal_stop"):
            ret, frame = cap.read()
            if not ret:
                break

            # cv2.imshow('RTSP Stream', frame)

            # 如果成功读取到帧
            if not is_gray_screen(frame):
                # self.on_frame(frame)
                yield frame

            if cv2.waitKey(1) & 0xFF == ord('q'):
                break

            # 按下 'q' 键退出循环
            if self.is_stop or not cap.isOpened():
                break

        # 释放资源
        cap.release()

    def stop(self):
        print("关闭循环")
        self.is_stop = True


def play_rtsp(rtsp_url):
    lj_stream_cv = LJStreamCv(rtsp_url)

    for frame in lj_stream_cv.start():
        cv2.imshow('RTSP Stream', frame)

    cv2.destroyAllWindows()


def capture_frame(url):
    if not url:
        return
    # 创建视频捕捉对象
    cap = cv2.VideoCapture(url)

    # 检查是否成功打开视频流
    if not cap.isOpened():
        print(f"无法打开视频流[{url}]")
        return

    # 设置读取第100
    # cap.set(cv2.CAP_PROP_POS_FRAMES, 1000)
    # 读取视频流的帧

    ret, frame = cap.read()

    i = 0
    while i < 100 and is_gray_screen(frame):
        i += 1
        ret, frame = cap.read()

    # 检查是否成功读取帧
    if not ret:
        print("无法读取帧")
        return

    img_path = gen_temp(frame)

    # 释放视频捕捉对象
    cap.release()

    return img_path


def gen_temp(frame):
    img_name = f"temp/{tool_id.gen_id()}.jpg"
    img_path = os.path.join(os.getcwd(), img_name)
    # 保存截图
    cv2.imwrite(img_name, frame)

    # cv2.imshow("截图", frame)
    # cv2.waitKey(0)

    return img_path


def is_gray_screen(frame):
    try:
        # 转换为灰度图像
        gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

        # 计算灰度直方图
        hist = cv2.calcHist([gray_frame], [0], None, [256], [0, 256])

        # 统计非零频数的灰度值个数
        non_zero_bins = cv2.countNonZero(hist)
        # 判断灰屏
        if non_zero_bins <= 500:
            return True
        else:
            return False
    except:
        return True
